//
//  LFTMCUtil.m
//  Pods
//
//  Created by Thomas Quan on 2017/5/11.
//
//

#import "LFTMCUtil.h"
#import <NIMSDK/NIMSDK.h>


static NSString *const isOnlySeeTeacher = @"isOnlySeeTeacher";
static NSString *const LFTMCSessionId   = @"LFTMCSessionId";
static NSString *const teacherIds       = @"teacherIds";
static NSString *const LFTMCUserId      = @"LFTMCUserId";

@implementation LFTMCUtil

static id _instance;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (LFTMCIdentity)identityFor:(NSString *)someone inSession:(NSString *)sessionId {
    NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:sessionId];
    NSString *serverCustomInfoString = team.serverCustomInfo;
    NSDictionary *serverCustomInfo = [LFTMCUtil stringToDictionary:serverCustomInfoString];
    NSArray *teachers;
    if (serverCustomInfo && serverCustomInfo[kTagTeachers]) {
        teachers = serverCustomInfo[kTagTeachers];
    }
    NSArray *assistans;
    if (serverCustomInfo && serverCustomInfo[kTagAssistans]) {
        assistans = serverCustomInfo[kTagAssistans];
    }

    NIMTeamMember *teamMember = [[NIMSDK sharedSDK].teamManager teamMember:someone inTeam:sessionId];
    if (![LFTMCUtil isOwnerOrManager:teamMember]) {
        return LFTMCIdentityNomal;
    }
    
    for (NSUInteger i=0; teachers && i<teachers.count; i++) {
        NSString *tid = [teachers[i] stringValue];
        if ([teachers[i] isKindOfClass:[NSNumber class]]) {
            tid = [NSString stringWithFormat:@"%@", teachers[i]];
        }
        if ([someone isEqualToString:tid]) {
            return LFTMCIdentityTeacher;
        }
    }
    
    for (NSUInteger i=0; assistans && i<assistans.count; i++) {
        NSString *aid = [assistans[i] stringValue];
        if ([assistans[i] isKindOfClass:[NSNumber class]]) {
            aid = [NSString stringWithFormat:@"%@", assistans[i]];
        }
        if ([someone isEqualToString:aid]) {
            return LFTMCIdentityAssistans;
        }
    }

    if (teamMember.type == NIMTeamMemberTypeOwner) {
        return LFTMCIdentityTeamOwner;
    }
    return LFTMCIdentityManager;
}

- (LFTMCSessionViewController *)lftmcSessionViewController {
    return self.lftmcVC;
}

+ (BOOL)isMe:(NSString *)uid {
    NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
    return [me isEqualToString:uid];
}


+ (NSArray *)teachersBySessionId:(NSString *)sessionId {
    NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:sessionId];
    NSString *serverCustomInfoString = team.serverCustomInfo;
    NSDictionary *servercustomInfo = [self stringToDictionary:serverCustomInfoString];
    NSArray *teachers;
    if (servercustomInfo && servercustomInfo[kTagTeachers]) {
        teachers = servercustomInfo[kTagTeachers];
    }
    return teachers;
}

/* 存储是否只看讲师的数组的每一项的数据格式
 *  dict:{
 *     LFTMCSessionId     :'xxxx',  // 记录聊天页的sessionId
 *     isOnlySeeTeacher   : YES,    // 记录该session的配置
 *     LFTMCUserId        :'yyyy'   // 记录当前登录人的Id
 *  }
 */

+ (BOOL)shouldOnlySeeTeacherBySessionId:(NSString *)sessionId {
    BOOL FLAG = NO;
    NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
    NSArray *sessions = [[NSUserDefaults standardUserDefaults] objectForKey:isOnlySeeTeacher];
    if (sessions == nil) {
        sessions = [[NSArray alloc] init];
        return FLAG;
    }
    
    if (!sessions.count) {
        NSDictionary *sample = [sessions firstObject];
        // 只保存一个用户的只看讲师记录
        if (![[sample objectForKey:LFTMCUserId] isEqualToString:me]) {
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:isOnlySeeTeacher];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return FLAG;
        }
    }
    
    for (NSDictionary *dict in sessions) {
        if ([dict objectForKey:LFTMCSessionId] &&
            [[dict objectForKey:LFTMCSessionId] isEqualToString:sessionId] &&
            [dict objectForKey:isOnlySeeTeacher]) {
            FLAG = [[dict objectForKey:isOnlySeeTeacher] boolValue];
            break;
        }
    }
    
    return FLAG;
}

+ (void)setOnlySeeTeacher:(BOOL)flag inSession:(NSString *)sessionId {
    
    NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
    NSArray *sessions = [[NSUserDefaults standardUserDefaults] objectForKey:isOnlySeeTeacher];
    
    NSMutableDictionary *mdict = [[NSMutableDictionary alloc] init];
    if (sessions == nil) {
        NSMutableArray *copy = [[NSMutableArray alloc] init];
        [mdict setObject:me forKey:LFTMCUserId];
        [mdict setObject:sessionId forKey:LFTMCSessionId];
        [mdict setObject:[NSNumber numberWithBool:flag] forKey:isOnlySeeTeacher];
        [copy addObject:mdict];
        [[NSUserDefaults standardUserDefaults] setObject:copy forKey:isOnlySeeTeacher];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return;
    }
    
    if (!sessions.count) {
        NSDictionary *sample = [sessions firstObject];
        // 只保存一个用户的只看讲师记录
        if (![[sample objectForKey:LFTMCUserId] isEqualToString:me]) {
            NSMutableArray *copy = [[NSMutableArray alloc] init];
            [mdict setObject:me forKey:LFTMCUserId];
            [mdict setObject:sessionId forKey:LFTMCSessionId];
            [mdict setObject:[NSNumber numberWithBool:flag] forKey:isOnlySeeTeacher];
            [copy addObject:mdict];
            [[NSUserDefaults standardUserDefaults] setObject:copy forKey:isOnlySeeTeacher];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return;
        }
    }
    
    BOOL isFind = NO;
    NSMutableArray *copy = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in sessions) {
        if ([dict objectForKey:LFTMCSessionId] &&
            [[dict objectForKey:LFTMCSessionId] isEqualToString:sessionId] &&
            [dict objectForKey:isOnlySeeTeacher]) {
                [mdict setObject:me forKey:LFTMCUserId];
                [mdict setObject:[NSNumber numberWithBool:flag] forKey:isOnlySeeTeacher];
                [mdict setObject:sessionId forKey:LFTMCSessionId];
                isFind = YES;
                [copy addObject:mdict];
                continue;
        }
        
        if ([dict objectForKey:LFTMCSessionId]) {
            [copy addObject:dict];
        }
        
    }
    if (isFind == NO) {
        [mdict setObject:me forKey:LFTMCUserId];
        [mdict setObject:[NSNumber numberWithBool:flag] forKey:isOnlySeeTeacher];
        [mdict setObject:sessionId forKey:LFTMCSessionId];
        [copy addObject:mdict];
    }
    [[NSUserDefaults standardUserDefaults] setObject:copy forKey:isOnlySeeTeacher];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

+ (NSArray<NIMMessage *> *)removeNotifications:(NSArray<NIMMessage *> *)messages {
    NSMutableArray *lftmcMsgs = [[NSMutableArray alloc] init];
    for (NIMMessage *message in messages) {
        if (message.messageType != NIMMessageTypeNotification) {
            [lftmcMsgs addObject:message];
            continue;
        }
        NIMNotificationObject *object = message.messageObject;
        NIMTeamNotificationContent *content = (NIMTeamNotificationContent*)object.content;
        id attachment = [content attachment];
        if ([attachment isKindOfClass:[NIMUpdateTeamInfoAttachment class]]) {
            NIMUpdateTeamInfoAttachment *teamAttachment = (NIMUpdateTeamInfoAttachment *)attachment;
            if ([teamAttachment.values count] == 1) {
                NIMTeamUpdateTag tag = [[[teamAttachment.values allKeys] firstObject] integerValue];
                if (tag == NIMTeamUpdateTagMuteMode) {
                    [lftmcMsgs addObject:message];
                }
            }
        }
    }
    return lftmcMsgs;
}

+ (NSArray *)filterMessages:(NSArray<NIMMessage *> *)messages
                  ByUserIds:(NSArray *)userIds
                isNeedModel:(BOOL)isNeedModel{
    
    __block NSMutableArray *array = [[NSMutableArray alloc] init];
    __block NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
    __block NSArray *uids = userIds;
    
    if (uids) {
        [messages enumerateObjectsUsingBlock:^(NIMMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            for (NSString *item in uids) {
                NSString *from = [obj from];
                
                NSString *uid;
                if ([item isKindOfClass:[NSNumber class]]) {
                    uid = [NSString stringWithFormat:@"%@", item];
                }
                
                
                if ([uid isEqualToString:from]) {
                    if (isNeedModel) {
                        NIMMessageModel *model = [[NIMMessageModel alloc] initWithMessage:obj];
                        [array addObject:model];
                    } else {
                        [array addObject:obj];
                    }
                    
                }
            }
            
        }];
    } else {
        [messages enumerateObjectsUsingBlock:^(NIMMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (isNeedModel) {
                NIMMessageModel *model = [[NIMMessageModel alloc] initWithMessage:obj];
                [array addObject:model];
            } else {
                [array addObject:obj];
            }
            
        }];
    }
    
    return array;
}

+ (NSArray *)filterMessages:(NSArray<NIMMessage *> *)messages
                  SessionId:(NSString *)sessionId
                isNeedModel:(BOOL)isNeedModel {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSArray *tids;
    if ([self shouldOnlySeeTeacherBySessionId:sessionId]) {
        tids = [self teachersBySessionId:sessionId];
    }
    NSArray *filteredArray = [self filterMessages:messages
                                        ByUserIds:tids
                                      isNeedModel:isNeedModel];
    return filteredArray;
}

+ (NSInteger)teamStatus:(NSDictionary *)customInfo {
    if (customInfo && [customInfo objectForKey:kTagStatus]) {
        NSInteger status = [customInfo[kTagStatus] integerValue];
        return status;
    }
    return 0;
}

+ (BOOL)isOwnerOrManager:(NIMTeamMember *)member {
    if (member.type == NIMTeamMemberTypeOwner ||
        member.type == NIMTeamMemberTypeManager) {
        return YES;
    }
    return NO;
}

+ (BOOL)isIMuted:(NSArray *)mutedArray {
    NSString *me = [[NIMSDK sharedSDK].loginManager currentAccount];
    for (NIMTeamMember *teamMember in mutedArray) {
        if ([teamMember.userId isEqualToString:me]) {
            return YES;
        }
    }
    return NO;
}

+ (LFTMCStatus)statusForTeamByModel:(LofterMvpCourseTeamModel *)teamModel mutedMembers:(NSArray *)members {
    NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:teamModel.teamId];
    NIMTeamMember *member = [[NIMSDK sharedSDK].teamManager teamMember:teamModel.teamId inTeam:teamModel.accountId];
    [[NIMSDK sharedSDK].teamManager fetchTeamMutedMembers:teamModel.teamId completion:^(NSError * _Nullable error, NSArray<NIMTeamMember *> * _Nullable members) {
        
    }];
    NSString *serverInfo = team.serverCustomInfo;
    NSDictionary *customInfo = [self stringToDictionary:serverInfo];
    
    if (teamModel.teamClosed  || [self teamStatus:customInfo]==0) {
        return LFTMCStatusCourseEnded;
    }
    if (team.inAllMuteMode) {
        return LFTMCStatusTeamMuted;
    }
    if (member.isMuted || [self isIMuted:members]) {
        return LFTMCStatusPersonMuted;
    }
    return LFTMCStatusNormal;
}

+ (NSDictionary *)stringToDictionary:(NSString *)string {
    if (string == nil) {
        return nil;
    }
    NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        //        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSString *)textByStatus:(LFTMCStatus) status {
    NSString *text;
    switch (status) {
        case LFTMCStatusNormal: {
            text = @"";
            break;
        }
        case LFTMCStatusPersonMuted:{
            text = @"您已被禁言";
            break;
        }
        case LFTMCStatusTeamMuted:{
            text = @"禁言模式已开启";
            break;
        }
        case LFTMCStatusCourseEnded:{
            text = @"互动已经结束";
            break;
        }
    }
    return text;
}

+ (NSString *)titleMaker: (NSString *)title {
    
    // 大于15字的部分不显示，用 "..." 代替
    NSUInteger upLimit = 15;
    if ([title length] <= upLimit) {
        return title;
    }
    
    title = [NSString stringWithFormat:@"%@...", [title substringToIndex:upLimit]];
    
    return title;
}

+ (UIImage *)scaleFromeImage:(UIImage *)image
                     toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaredImage;
    
}

+ (CGSize)scaredImageWithImageOriginSize:(CGSize)imageSize
                                  maxSize:(CGSize)maxSize
{
    CGSize size;
    NSInteger imageWidth = imageSize.width ,imageHeight = imageSize.height;
    NSInteger imageMaxWidth = maxSize.width, imageMaxHeight = maxSize.height;
    if (imageWidth > imageHeight) //宽图
    {
        size.height = imageHeight;  //高度取最小高度
        size.width = imageWidth;
        if (size.width > imageMaxWidth)
        {
            size.width = imageMaxWidth;
            size.height = imageMaxWidth * imageHeight / imageWidth;
        }
    }
    else if(imageWidth < imageHeight)//高图
    {
        size.width = imageWidth;
        size.height = imageHeight;
        if (size.height > imageMaxHeight)
        {
            size.height = imageMaxHeight;
            size.width = imageWidth * imageMaxHeight / imageHeight;
        }
    }
    else//方图
    {
        if (imageWidth > imageMaxWidth)
        {
            size.width = imageMaxWidth;
            size.height = imageMaxHeight;
        }
        else
        {
            size.width = imageWidth;
            size.height = imageHeight;
        }
    }
    return size;
}

+ (BOOL)shouldScrollToButtom:(UIScrollView *)scrollView {
    if ((scrollView.contentOffset.y + scrollView.frame.size.height + 140) - scrollView.contentSize.height >= DBL_EPSILON) {
        return YES;
    }
    return NO;
}

@end
